var rootPath = '';//kk.getRootPath();

/* roleDom */
var roleDom = '\
<form class="form-horizontal" id="roleForm">\
	<div>\
		<input type="hidden" name="id" />\
	</div>\
	<div class="form-group">\
		<label for="name" class="col-sm-2 control-label">名称<span class="text-red">*</span></label>\
		<div class="col-sm-10">\
			<input type="text" class="form-control" id="name" name="name" placeholder="名称">\
		</div>\
	</div>\
	<div class="form-group">\
		<label for="description" class="col-sm-2 control-label">描述</label>\
		<div class="col-sm-10">\
			<textarea class="form-control" rows="6" id="description" name="description" placeholder="描述"></textarea>\
		</div>\
	</div>\
</form>\
';

/* CRUD 1: Create, 2: Read, 3: Update, 4: Delete */
var CREATE = 1, READ = 2, UPDATE = 3, DELETE = 4;
function CRUDRoleFunc(operCode, id, index) {
	var canOpen = false;
	var url;
	var obj;
	
	if (operCode == CREATE) {
		canOpen = true;
	} else if (operCode == READ || operCode == UPDATE) {
		url = rootPath + '/Admin/Role/find?id=' + id;
		obj = kk.getObj(url);
		if (obj != null) {
			canOpen = true;
		}
	} else if (operCode == DELETE) {
		url = rootPath + '/Admin/Role/delete?id=' + id;
		kk.deleteObj(url, '#table');
	} else {
		return false;
	}
	
	if (!canOpen) {
		return false;
	}
	
	var validator;
	
	xpopup.window({
	    width: 800,
	    content: roleDom,
        buttons: [{
        	id:	'btnOk',
            text: '确定',
            'class': 'btn btn-info btn-flat',
            handler: function ($this) {
    	 		if (validator.form() && doCU(operCode, id, index)) {
            		$this.destroy();
    	 		}
            }
        }, {
        	id:	'btnCancel',
            text: '取消',
            'class': 'btn btn-default btn-flat',
            handler: function ($this) {
        		$this.destroy();
            }
        }],
        afterShow: function ($this) {
			if (operCode == CREATE) {
				$this.setTitle('添加');
			} else if (operCode == READ) {
				$this.setTitle('查看');
				$('#btnOk').hide();
	    		$('#btnCancel').text('关闭');

				$('#roleForm').setForm(obj);

				$('#roleForm').find(':input').attr("disabled", "disabled");		// 习惯性地处理
			} else if (operCode == UPDATE) {
				$this.setTitle('编辑');
				
				$('#roleForm').setForm(obj);
			}

        	validator = $("#roleForm").validate({
    			onfocusout: function(element) {
    				$(element).valid();
    			},
                rules: {
        			name: "required",
                },
                messages: {
        			name: "请输入名称",
                }
            });
        }
	});
}

/* Create & Update */
function doCU(operCode, id, index) {
    var url;
    var method;
	var jsonStr = JSON.stringify($('#roleForm').serializeObject());
	var result;
	
	if (operCode == CREATE) {
		url = rootPath + '/Admin/Role/save';
		method = "POST";

		result = kk.doStrAjax(url, method, jsonStr);
	    if (result.code == 0) {
	    	$('#table').bootstrapTable('insertRow', {
				index: 0,
	    		row: result.obj
			});
	    	
	    	return true;
		}
	} else if (operCode == UPDATE) {
		url = rootPath + '/Admin/Role/update?id=' + id;
		method = "PUT";

		result = kk.doStrAjax(url, method, jsonStr);
	    if (result.code == 0) {
	    	$('#table').bootstrapTable('updateRow', {
	    		index: index,
	    		row: result.obj
	    	});
	    	
	    	return true;
		}
	}
	
	return false;
}


/* configure menu for role */
var addMenusDom = '\
	<div class="alert alert-warning alert-dismissible fade in" role="alert">\
		<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>\
		<h4>注意!</h4>\
		<p>变更授权后，需要用户重新登录授权才可生效。</p>\
	</div>\
	<ul id="menuTree" class="ztree"></ul>\
';

function addMenus(id, index) {
	var zTreeObj;
	var result;
	
	xpopup.window({
	    width: 800,
	    height: 600,
		title: '查看',
	    content: addMenusDom,
        buttons: [{
            	id:	'btnOk',
                text: '确定',
                'class': 'btn btn-info btn-flat',
                handler: function ($this) {
                	// resIdList
					var checkednodes = zTreeObj.getCheckedNodes(true);
                    var resIdList = new Array();
					for (var i = 0; i < checkednodes.length; i++) {
                    	resIdList.push(parseInt(checkednodes[i].id));
					}
				    var jsonStr = JSON.stringify(resIdList);

				    var url = rootPath + '/Admin/Role/addMenus?id=' + id;

					result = kk.doStrAjax(url, "PUT", jsonStr);
				    if (result.code == 0) {
				    	$('#table').bootstrapTable('updateRow', {
				    		index: index,
				    		row: result.obj
				    	});
				    	$this.destroy();
				    }
                }
            }, {
            	id:	'btnCancel',
                text: '取消',
                'class': 'btn btn-default btn-flat',
                handler: function ($this) {
            		$this.destroy();
                }
            }
		],
        afterShow: function ($this) {
        	var setting = {
				async: {
					enable: true,
					type: "get",
					url: rootPath + '/Admin/Menu/getAll',
					autoParam: ["id", "name"],
					dataFilter: ajaxDataFilter
				},
				callback: {
					onAsyncSuccess: zTreeOnAsyncSuccess
				}, 
				check: {
					enable: true
				}, 
				data: {
					simpleData: {
						enable: true,
						idKey: "id",
						pIdKey: "pid",
						rootPId: 0
					}
				}
			};
        	
        	function ajaxDataFilter(treeId, parentNode, responseData) {
        	    return responseData.obj;
        	}

		    var url = rootPath + '/Admin/Menu/getMenuIds4Role?roleId=' + id;
        	var menuIds = kk.getObj(url);
        	function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {		// 加载成功后打勾
				for (var i in menuIds) {
					var node = zTreeObj.getNodeByParam("id", menuIds[i]);
					if (node && !node.isParent) {									// 只给叶子选择节点+++
						zTreeObj.checkNode(node, true, true);
					}
				}
        	}

        	zTreeObj = $.fn.zTree.init($("#menuTree"), setting);
        }
	});
}
